package com.lottery.ruok.lottrey.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.lottery.ruok.lottrey.R;
import com.lottery.ruok.lottrey.dialog.PasswordDialog;
import com.lottery.ruok.lottrey.retrofitModule.RetrofitBase;
import com.lottery.ruok.lottrey.retrofitModule.RxHelper;
import com.lottery.ruok.lottrey.retrofitModule.RxSubscribe;
import com.lottery.ruok.lottrey.retrofitModule.request.GetRoomUsersRequest;
import com.lottery.ruok.lottrey.retrofitModule.response.GetProfileResponse;
import com.lottery.ruok.lottrey.retrofitModule.response.GetRoomUsersResponse;
import com.lottery.ruok.lottrey.userInfo.UserInfo;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.rong.imlib.model.Conversation;
import utils.Utils;
/*
* 发红包
* */

public class SendRedPacketActivity extends BaseActivity implements TextWatcher{
    public static final int TYPE_PRIVITE = 1;
    public static final int TYPE_GROUP_NORMAL = 2;
    public static final int TYPE_GROUP_RANDOM = 3;
    public static final String EXTRA_TYPE = "extra_type";
    public static final String EXTRA_TARGET_ID = "extra_target_id";


    @BindView(R.id.descp)
    TextView descp;
    @BindView(R.id.change_type)
    TextView changeType;
    @BindView(R.id.money_title)
    TextView moneyTitle;
    @BindView(R.id.single_packet_money)
    EditText singlePacketMoney;
    @BindView(R.id.all_account)
    TextView allAccount;
    @BindView(R.id.packet_num)
    EditText packetNum;
    @BindView(R.id.people_num)
    TextView peopleNum;
    @BindView(R.id.blessing)
    EditText blessing;
    @BindView(R.id.total_money)
    TextView totalMoney;
    @BindView(R.id.confirm)
    TextView confirm;

    private int pocketType = 2;//2是群发红包_普通，3是群发红包_拼手气，1是单独发红包
    private String targetId;//单独发红包是对方id，群红包是房间id

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_send_red);
        ButterKnife.bind(this);
        init();
        initView();
        load();
    }


    private void init() {
        Intent intent = getIntent();
        if (intent != null) {
            pocketType = intent.getIntExtra(EXTRA_TYPE, TYPE_GROUP_NORMAL);
            targetId = intent.getStringExtra(EXTRA_TARGET_ID);
        }
    }

    private void initView() {
        singlePacketMoney.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.toString().contains(".")) {
                    if (s.length() - 1 - s.toString().indexOf(".") > 2) {
                        s = s.toString().subSequence(0,
                                s.toString().indexOf(".") + 3);
                        singlePacketMoney.setText(s);
                        singlePacketMoney.setSelection(s.length());
                    }
                }
                if (s.toString().trim().substring(0).equals(".")) {
                    s = "0" + s;
                    singlePacketMoney.setText(s);
                    singlePacketMoney.setSelection(2);
                }

                if (s.toString().startsWith("0")
                        && s.toString().trim().length() > 1) {
                    if (!s.toString().substring(1, 2).equals(".")) {
                        singlePacketMoney.setText(s.subSequence(0, 1));
                        singlePacketMoney.setSelection(1);
                        return;
                    }
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
                listenToInput();
            }
        });
        packetNum.addTextChangedListener(this);
    }

    private void load() {
        RetrofitBase.getRetrofit().create(GetRoomUsersRequest.class)
                .getResult(UserInfo.getToken(), UserInfo.getRoomId(), null, 1000000, 0)
                .compose(RxHelper.<GetRoomUsersResponse>handleResult())
                .subscribeWith(new RxSubscribe<GetRoomUsersResponse>(this) {
                    @Override
                    protected void _onNext(GetRoomUsersResponse getRoomUsersResponses) {
                        peopleNum.setText(String.format("聊天室共%d人", getRoomUsersResponses.getCount()));
                    }

                    @Override
                    protected boolean showDialog() {
                        return false;
                    }
                });
    }
    @Override
    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void onTextChanged(CharSequence s, int i, int i1, int i2) {
    }

    @Override
    public void afterTextChanged(Editable editable) {

       listenToInput();
    }

    private void listenToInput(){
        if(packetNum.getText().toString().equals("")
                || singlePacketMoney.getText().toString().equals("")
                || singlePacketMoney.getText().toString().equals(".")
                || Integer.parseInt(packetNum.getText().toString()) == 0
                || Double.parseDouble(singlePacketMoney.getText().toString()) == 0f){
            confirm.setTextColor(Color.parseColor("#7E33CD"));
            confirm.setEnabled(false);

            totalMoney.setText(0 + "");
        } else {
            confirm.setTextColor(Color.parseColor("#ffffff"));
            confirm.setEnabled(true);

            if(pocketType == 2) {
                totalMoney.setText(Utils.saveTwoFormat(Integer.parseInt(packetNum.getText().toString()) * Double.parseDouble(singlePacketMoney.getText().toString())) + "");
            } else if(pocketType == 3){
                totalMoney.setText(Utils.saveTwoFormat(Double.parseDouble(singlePacketMoney.getText().toString())));
            }
        }
    }

    @OnClick({R.id.change_type, R.id.all_account, R.id.confirm})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.change_type:
                if(pocketType == 2){
                    pocketType = 3;

                    descp.setText("当前为拼手气红包，");
                    changeType.setText("改为普通红包");
                    moneyTitle.setText("总金额");
                } else {
                    pocketType = 2;

                    descp.setText("当前为普通红包，");
                    changeType.setText("改为拼手气红包");
                    moneyTitle.setText("单个金额");
                }
                listenToInput();
                break;
            case R.id.all_account:
                if(pocketType == 2){
                    if(packetNum.getText().toString().equals("")
                            || Integer.parseInt(packetNum.getText().toString()) == 0){
                        Utils.showToast("请输入红包个数");
                    } else {
                        singlePacketMoney.setText(Utils.saveTwoFormat(Double.parseDouble(UserInfo.getAccount()) * 1.0 / Integer.parseInt(packetNum.getText().toString())));
                    }
                } else if(pocketType == 3){
                    singlePacketMoney.setText(UserInfo.getAccount());
                }
                listenToInput();
                break;
            case R.id.confirm:
                updateAccount(new AfterUpdateAccount() {
                    @Override
                    public void afterUpdateAccount(GetProfileResponse getProfileResponse) {
                        if (getProfileResponse.getUser().getWithdraw_password() == 1) {
                            PasswordDialog passwordDialog = new PasswordDialog();
                            Bundle bundle = new Bundle();
                            bundle.putInt(PasswordDialog.TYPE, 1);
                            bundle.putInt(PasswordDialog.POCKET_TYPE, pocketType);
                            bundle.putDouble(PasswordDialog.AMOUNT, Double.parseDouble(totalMoney.getText().toString()));
                            bundle.putDouble(PasswordDialog.PER_AMOUNT, Double.parseDouble(singlePacketMoney.getText().toString()));
                            bundle.putInt(PasswordDialog.NUMBERS, Integer.parseInt(packetNum.getText().toString()));
                            bundle.putString(PasswordDialog.DESC, blessing.getText().toString());
                            bundle.putString(PasswordDialog.TARGET_ID, targetId);
                            passwordDialog.setArguments(bundle);
                            passwordDialog.show(getSupportFragmentManager(), null);
                        } else {
                            Utils.showToast("您没有设置资金密码，请前往设置");
                        }
                    }
                }, true);
                break;
        }
    }

    public static void startActivity(Context context, String targetId, Conversation.ConversationType conversationType) {
        int type = 0;
        switch (conversationType) {
            case CHATROOM://群聊
                type = SendRedPacketActivity.TYPE_GROUP_NORMAL;
                break;
            case PRIVATE://单聊
                type = SendRedPacketActivity.TYPE_PRIVITE;
                break;
        }
        Intent intent = new Intent(context, SendRedPacketActivity.class);
        intent.putExtra(EXTRA_TYPE, type);
        intent.putExtra(EXTRA_TARGET_ID, targetId);
        context.startActivity(intent);
    }
}
